﻿using AutoMapper;
using MediatR;
using Traceability.Domain;
using Traceability.ErrorCode;
using Traceability.Infrastructure;

namespace Traceability.App.Applications.Aquaculture
{
    public class AquacultureAddCommandHandler : IRequestHandler<AquacultureAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Aquaculture> aquacRepository;
        private readonly IBaseRepository<T_Traceability> tranceRepository;
        private readonly IMapper mapper;
        public AquacultureAddCommandHandler(IBaseRepository<T_Aquaculture> aquacRepository, IMapper mapper, IBaseRepository<T_Traceability> tranceRepository)
        {
            this.aquacRepository = aquacRepository;
            this.mapper = mapper;
            this.tranceRepository = tranceRepository;
        }

        public async Task<APIResult<int>> Handle(AquacultureAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
          
            var model = mapper.Map<T_Aquaculture>(request);
            var record = aquacRepository.GetAll().FirstOrDefault(x => x.Batch == request.Batch);
            if (record==null)
            {
                model.ID = 0;
                result.Message = "添加成功";
                result.Data = await aquacRepository.Add(model);
                var data = tranceRepository.GetAll().FirstOrDefault(x => x.Batch == request.Batch);
                data.Perfection += 30;
                await tranceRepository.Update(data);
                return await Task.FromResult(result);
            }
            else 
            {
                result.Message = "修改成功";
                var models=mapper.Map(request, record);
                result.Data = await aquacRepository.Update(models);
                return await Task.FromResult(result);
            }
            
        }
    }
}
